# -*- coding: utf-8 -*-
from utils.config import *
from utils.utils import *
import pandas as pd
import utils.MyTT as Mytt
# import logging
from utils.log import Loggers
from utils.pushService import PushService
import numpy as np

# 每小时的前5分钟 不调用脚本，防止数据不完整
should_skip()
logger = Loggers('junxianFasan')
# logger.clear()

pushSer = PushService('均线高质量多空策略')

# 动态调整ATR倍数（根据市场波动率）
def dynamic_multiplier(atr_ratio):
    # atr_ratio = myAtr / YearAtr
    if atr_ratio > 1.5:  # 高波动期
        return 1.5  
    elif atr_ratio < 0.7: # 低波动期
        return 3
    else:
        return 2.5

# 计算止损点位，使用动态atr 进行止损计算
def getZhisun(after_signal):
        # 动态计算小数位
    xiaoshuwei = 1 if after_signal['close']>0 else 4
    atr_value = dynamic_multiplier(after_signal['atr40']/after_signal['atr130']) * after_signal['atr40']
    value = (   atr_value if after_signal['signal'] <0 else  atr_value*-1)
    return round(after_signal['close'] + value,xiaoshuwei), round(after_signal['close'] - value,xiaoshuwei)
    
firstOne = 0
# 循环处理
for instId in config_movingAverage_instId:
    # 读取300条最新的数据
    try:
        df = loadCsvData(instId,'1d',300)
    except:
        continue

    # 计算指标 唐奇安通道  上轨和 下轨
    df['ma10']= Mytt.EMA(df['close'],10)
    df['ma20']= Mytt.EMA(df['close'],20)
    df['ma60']= Mytt.EMA(df['close'],60)
    df['ma120']= Mytt.EMA(df['close'],120)

    df['atr'] = Mytt.ATR(df['close'],df['high'],df['low'],20)
    # 计算布林带
    df['boll_up'],_,df['boll_low'] = Mytt.BOLL(df['close'],20,2)

    # 计算金叉死叉 默认无交叉
    df['cross_60'] = 0 
    df['cross_60'] = Mytt.CROSS(df['ma60'],df['ma120'])
    df['cross_60'] = Mytt.VALUEWHEN(df['cross_60']!=0,df['cross_60'])

    # 计算小周期的金叉死叉
    # df['cross_10'] = Mytt.CROSS(df['ma10'],df['ma20'])
    # 价格站上10均线
    df['cross_close'] = Mytt.CROSS(df['close'],df['ma10'])

    # 计算最近低点
    df['recent_low'] = Mytt.LLV(df['low'],10)

    # 寻找开单信号
    df['signal'] = 0 
    # 做多信号  大级别多头趋势，收盘价>10均线 ，最高价不超过布林带上轨
    df.loc[(df['cross_60'] == 1) & (df['cross_close'] == 1) & (df['high']<df['boll_up'])  ,'signal'] = 1
    df.loc[(df['cross_60'] == -1) & (df['cross_close'] == -1) & (df['low']>df['boll_low'])  ,'signal'] = -1
    
    # 快速计算信号近期胜率
    # shenglv5,shenglv10 = getShenglv(df)
    # 取出所有满足条件的信号数据
    df_signal = df[df['signal']!=0]
    # print(df_signal.tail(30))
    # print(len(df_signal))
    # exit()
    # 拿到最后出现信号的数据
    after_signal = df_signal.iloc[-1]

    xiaoshu = 1 if after_signal['close']>0 else 3
    # 计算止损点位
    zhisun= round(after_signal['recent_low'] + (after_signal['atr'] if after_signal['signal'] == -1 else after_signal['atr']*-1),xiaoshu)

    fangxiang = '做多' if after_signal['signal']>0 else '做空'
    signal_text = f"{instId}{fangxiang} 最近信号：{after_signal.name} 收盘价：{after_signal['close']} "

    # 计算止损位置
    zhisunR = round( abs((zhisun - after_signal['close'])) /after_signal['close'] *100,2)

    signal_text+= f"止损：{zhisun}({zhisunR}%)"
    hour = getHoursPassed(after_signal.name)
    # 进行日志记录
    if hour < 25:
        if firstOne == 0:
            firstOne=1
            extent = [
            f"止损：{zhisun}({zhisunR}%)\n\n",
            "温馨提示：\n\n",
            "入场建议等价格回到ema10均线附近挂单\n\n",
            "当收盘价突破布林带上下轨，建议止盈\n\n",
            f"需要留意EMA60均线趋势，如果和交易方向相反，请放弃此单",
        ]
        else:
            extent = [
            f"止损：{zhisun}({zhisunR}%)\n\n",
        ]
        # 25小时内的新信号 就可以 进行钉钉推送
        if pushSer.add_push_item(after_signal, instId,extent):
            logger.info(signal_text)

    # 完成消息的通知
pushSer.push_message()

